import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:provider/provider.dart';
import '../core/douban_service.dart';
import '../core/models.dart';
import '../core/theme_config.dart';
import 'detail_page.dart';

class SearchPage extends StatefulWidget {
  const SearchPage({super.key});

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  final TextEditingController _searchController = TextEditingController();
  final FocusNode _searchFocus = FocusNode();
  List<String> _searchHistory = [];
  List<VodItem> _searchResults = [];
  bool _loading = false;
  bool _hasSearched = false;
  bool _loadingMore = false;
  int _currentPage = 0;
  bool _hasMore = true;

  @override
  void initState() {
    super.initState();
    _loadSearchHistory();
  }

  @override
  void dispose() {
    _searchController.dispose();
    _searchFocus.dispose();
    super.dispose();
  }

  Future<void> _loadSearchHistory() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      _searchHistory = prefs.getStringList('search_history') ?? [];
      if (mounted) setState(() {});
    } catch (_) {}
  }

  Future<void> _saveSearchHistory(String keyword) async {
    if (keyword.isEmpty) return;
    try {
      final prefs = await SharedPreferences.getInstance();
      _searchHistory.remove(keyword);
      _searchHistory.insert(0, keyword);
      if (_searchHistory.length > 20) {
        _searchHistory = _searchHistory.take(20).toList();
      }
      await prefs.setStringList('search_history', _searchHistory);
      if (mounted) setState(() {});
    } catch (_) {}
  }

  Future<void> _clearSearchHistory() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove('search_history');
      _searchHistory = [];
      if (mounted) setState(() {});
    } catch (_) {}
  }

  Future<void> _performSearch(String keyword) async {
    if (keyword.isEmpty) return;
    
    setState(() {
      _loading = true;
      _hasSearched = true;
      _currentPage = 0;
      _hasMore = true;
    });

    try {
      // 保存搜索历史
      await _saveSearchHistory(keyword);
      
      // 执行搜索
      final results = await DoubanService.searchMovies(
        query: keyword,
        start: 0,
        count: 20,
      );

      setState(() {
        _searchResults = results;
        _loading = false;
        _hasMore = results.length >= 20; // 如果返回结果少于20条，说明没有更多了
      });
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('搜索失败: $e')),
        );
      }
      setState(() => _loading = false);
    }
  }

  Future<void> _loadMore() async {
    if (_loadingMore || !_hasMore) return;
    
    setState(() {
      _loadingMore = true;
    });

    try {
      final keyword = _searchController.text;
      final nextPage = _currentPage + 1;
      
      final results = await DoubanService.searchMovies(
        query: keyword,
        start: nextPage * 20,
        count: 20,
      );

      setState(() {
        _searchResults.addAll(results);
        _currentPage = nextPage;
        _loadingMore = false;
        _hasMore = results.length >= 20; // 如果返回结果少于20条，说明没有更多了
      });
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载更多失败: $e')),
        );
      }
      setState(() => _loadingMore = false);
    }
  }

  void _onHistoryItemTap(String keyword) {
    _searchController.text = keyword;
    _performSearch(keyword);
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<ThemeConfig>(
      builder: (context, themeConfig, child) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('影视搜索'),
            //居中
            centerTitle: true,
            leading: IconButton(
              icon: const Icon(Icons.arrow_back),
              onPressed: () => Navigator.of(context).pop(),
            ),
            backgroundColor: themeConfig.currentGradient.colors.first,
            elevation: 0,
            foregroundColor: themeConfig.currentTextColor,
          ),
          body: Container(
            decoration: BoxDecoration(
              gradient: themeConfig.currentGradient,
            ),
            child: Column(
              children: [
                // 搜索框
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                  child: TextField(
                    controller: _searchController,
                    focusNode: _searchFocus,
                    decoration: InputDecoration(
                      hintText: '请输入关键词搜索',
                      prefixIcon: const Icon(Icons.search, size: 20),
                      suffixIcon: _searchController.text.isNotEmpty
                          ? IconButton(
                              icon: const Icon(Icons.clear, size: 20),
                              onPressed: () {
                                _searchController.clear();
                                setState(() {});
                              },
                            )
                          : null,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(20.0),
                      ),
                      contentPadding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0),
                      isDense: true,
                    ),
                    onSubmitted: _performSearch,
                    onChanged: (_) => setState(() {}),
                  ),
                ),

                // 搜索结果或搜索历史
                Expanded(
                  child: _hasSearched
                      ? _buildSearchResults()
                      : _buildSearchHistory(),
                ),
              ],
            ),
          ),
        );
      }
    );
  }

  Widget _buildSearchHistory() {
    return Consumer<ThemeConfig>(
      builder: (context, themeConfig, child) {
        if (_searchHistory.isEmpty) {
          return Center(
            child: Text('暂无搜索历史', style: TextStyle(color: themeConfig.currentTextColor)),
          );
        }

        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '搜索历史',
                    style: TextStyle(
                      fontWeight: FontWeight.bold, 
                      fontSize: 16,
                      color: themeConfig.currentTextColor,
                    ),
                  ),
                  TextButton(
                    onPressed: _clearSearchHistory,
                    child: Text('清除', style: TextStyle(color: themeConfig.currentTextColor)),
                  ),
                ],
              ),
            ),
        Expanded(
          child: SingleChildScrollView(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Wrap(
              spacing: 8.0,
              runSpacing: 8.0,
              children: _searchHistory.map((keyword) {
                return Consumer<ThemeConfig>(
                  builder: (context, themeConfig, child) {
                    return Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        ActionChip(
                          avatar: Icon(Icons.history, size: 16, color: themeConfig.currentTextColor),
                          label: Text(keyword, style: TextStyle(color: themeConfig.currentTextColor)),
                          backgroundColor: themeConfig.currentTextColor.withOpacity(0.2),
                          onPressed: () => _onHistoryItemTap(keyword),
                        ),
                        IconButton(
                          icon: Icon(Icons.close, size: 16, color: themeConfig.currentTextColor),
                          onPressed: () async {
                            final prefs = await SharedPreferences.getInstance();
                            _searchHistory.remove(keyword);
                            await prefs.setStringList('search_history', _searchHistory);
                            setState(() {});
                          },
                        ),
                      ],
                    );
                  }
                );
              }).toList(),
            ),
          ),
        ),
      ],
    );
      }
    );
  }

  Widget _buildSearchResults() {
    if (_loading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_searchResults.isEmpty) {
      return Consumer<ThemeConfig>(
        builder: (context, themeConfig, child) {
          return Center(
            child: Text('暂无搜索结果', style: TextStyle(color: themeConfig.currentTextColor)),
          );
        }
      );
    }

    return CustomScrollView(
      slivers: [
        SliverPadding(
          padding: const EdgeInsets.all(16.0),
          sliver: SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: MediaQuery.of(context).size.width >= 1000 ? 6 : 3,
              childAspectRatio: 0.66,
              mainAxisSpacing: 12,
              crossAxisSpacing: 12,
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                if (index < _searchResults.length) {
                  final item = _searchResults[index];
                  final subtitle = [item.typeName, item.year, item.area, item.remarks]
                      .where((e) => (e ?? '').isNotEmpty)
                      .join(' · ');
                  
                  return _PosterCard(
                    title: item.name,
                    subtitle: subtitle,
                    imageUrl: item.pic,
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (_) => DetailPage(keyword: item.name),
                        ),
                      );
                    },
                  );
                } else {
                  return null;
                }
              },
              childCount: _searchResults.length + (_hasMore ? 1 : 0),
            ),
          ),
        ),
        if (_hasMore)
          SliverToBoxAdapter(
            child: Padding(
              padding: const EdgeInsets.only(bottom: 24.0),
              child: Center(
                child: _loadingMore
                    ? const CircularProgressIndicator()
                    : Consumer<ThemeConfig>(
                        builder: (context, themeConfig, child) {
                          return ElevatedButton(
                            onPressed: _loadMore,
                            style: ElevatedButton.styleFrom(
                              backgroundColor: themeConfig.currentTextColor.withOpacity(0.2),
                              foregroundColor: themeConfig.currentTextColor,
                              padding: const EdgeInsets.symmetric(
                                horizontal: 24,
                                vertical: 12,
                              ),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8),
                              ),
                            ),
                            child: const Text('加载更多'),
                          );
                        }
                      ),
              ),
            ),
          ),
      ],
    );
  }
}

class _PosterCard extends StatelessWidget {
  final String title;
  final String subtitle;
  final String? imageUrl;
  final VoidCallback onTap;
  const _PosterCard({
    required this.title,
    required this.subtitle,
    required this.imageUrl,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(12),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: const [
            BoxShadow(color: Color(0x11000000), blurRadius: 8, offset: Offset(0, 3)),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: ClipRRect(
                borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
                child: imageUrl == null
                    ? Container(color: Colors.black12, child: const Center(child: Icon(Icons.movie, size: 40)))
                    : CachedNetworkImage(
                        imageUrl: imageUrl!,
                        fit: BoxFit.cover,
                        width: double.infinity,
                        httpHeaders: const {
                          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                          'Referer': 'https://movie.douban.com/',
                        },
                        placeholder: (context, url) => Container(
                          color: Colors.black12,
                          child: const Center(child: CircularProgressIndicator()),
                        ),
                        errorWidget: (context, url, error) => Container(
                          color: Colors.black12,
                          child: const Center(child: Icon(Icons.movie, size: 40)),
                        ),
                      ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(title, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontWeight: FontWeight.w600)),
                  const SizedBox(height: 4),
                  Text(subtitle, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: Colors.black54, fontSize: 12)),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}